<?php

/**
 * Created by PhpStorm.
 * User: jimmy.chen
 * Date: 17/4/14
 * Time: 10:31
 */
class BBNotifySDK {

    /**
     * 签名算法
     *
     * @param array $params
     * @param $secret
     * @return string
     */
    public function genSign(array $params, $secret) {
        if (isset($params['sign'])) {
            unset($params['sign']); // 将sign字段置空
        }

        ksort($params);
        $sign_str = $secret; // 首部拼接上secret
        foreach ($params as $k => $v) {
            $sign_str .= "$k$v"; // 参数key与value进行拼接
        }
        $sign_str .= $secret; // 尾部拼接上secret
        $sign = md5($sign_str); // md5拼接好的字符串

        return strtoupper($sign); // 转换成大写
    }

    /**
     * 响应报文
     *
     * @param $success
     * @param string $message
     * @param null $data
     * @param string $err_code
     * @param string $err_msg
     */
    public function response($success, $message = '', $data = NULL, $err_code = '', $err_msg = '') {
        header('Content-Type: application/json; charset=utf-8');
        $resp = array(
            'success' => (bool) $success,
            'message' => $message,
            'data' => $data,
            'err_code' => $err_code,
            'err_msg' => $err_msg,
        );

        // 如不想退出，请用return json_encode($resp);
        exit(json_encode($resp));
    }
}

// 推送报文
$_POST = array(
    'method' => 'beibei.outer.trade.order.status.waitforship.notify',
    'app_id' => 'ejii',
    'id' => '4cdbc040-657a-4847-b266-7e31d9e2c3d9',
    'timestamp' => '1489046698',
    'session' => '2470bebc2440810054bc784d3ba39',
    'data' => '{"oid":"1234567890123456789","status":"1"}',
    'sign' => '7DEBA8701995E264828AB649FD1EE399',
);

$post_data = $_POST;
$bb = new BBNotifySDK();
if (!$post_data) {
    $bb->response(FALSE, '错误的消息');
}

if (!isset($post_data['sign'])) {
    $bb->response(FALSE, '无效的数据');
}

if ($post_data['sign'] != $bb->genSign($post_data, 'test')) {
    $bb->response(FALSE, '签名不正确');
}

$data = $post_data['data'];
$data = json_decode($data);

// 处理逻辑开始

// 处理逻辑结束

$bb->response(TRUE, '消息已收到');
